import logging

from flask import Blueprint, request
from flask import jsonify

from airflow.patsnap.service import role_service
from airflow.models.idata_auth_role import AuthRole
from airflow.utils.session import create_session
from airflow.www.api import exception_handle

log = logging.getLogger(__name__)

api_speech_role = Blueprint('api_speech_role', __name__)


@api_speech_role.route('/roles/<int:rid>', methods=['GET'])
@exception_handle
def get_role(rid):
    role = role_service.get_role(rid)
    return jsonify(code=0, message='ok', data=AuthRole.to_json(role))


@api_speech_role.route('/roles', methods=['GET'])
@exception_handle
def get_roles():
    page = request.args.get('page', 0, type=int)
    result = role_service.get_roles(page)
    return jsonify(code=0, message='ok', data=result)


@api_speech_role.route('/roles', methods=['POST'])
@exception_handle
def add_role():
    role = request.json
    role_name = role['role_name']
    weight = role['weight']
    resource_ids = role['resources']
    if role_name is None:
        log.error("add_role error role_name=%s", role_name, )
        return jsonify(code=400, message="add_role error name=None", data=None)
    if weight is None:
        log.error("add_role error weight=%s", weight, )
        return jsonify(code=400, message="add_role error url_prefix=None", data=None)

    role_service.add_role(role_name, weight, resource_ids)
    return jsonify(code=0, message='ok', data=None)


@api_speech_role.route('/roles/<int:id>', methods=['DELETE'])
@exception_handle
def delete_role(id):
    role_service.delete_role(id)
    return jsonify(code=0, message='ok', data=None)


@api_speech_role.route('/roles', methods=['PUT'])
@exception_handle
def update_role():
    role = request.json
    id = role['id']
    role_name = role['role_name']
    weight = role['weight']
    resource_ids = role['resources']
    if id is None:
        log.error("update_role error id=%s", id, )
        return jsonify(code=400, message="add_role error id=None", data=None)
    if role_name is None:
        log.error("update_role error role_name=%s", role_name, )
        return jsonify(code=400, message="add_role error role_name=None", data=None)
    if weight is None:
        log.error("update_role error weight=%s", weight, )
        return jsonify(code=400, message="add_role error weight=None", data=None)

    role_service.update_role(id, role_name, weight, resource_ids)
    return jsonify(code=0, message='ok', data=None)
